import ArticleItem from '@/components/ArticleItem';
import { useAppSelector } from '@/store';
import {
  ClearListByIdAction,
  SaveHomeListByIdAction,
} from '@/store/action/articles';
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
type ArticleListPropsType = {
  channel_id: number;
};

export default function ArticleList({ channel_id }: ArticleListPropsType) {
  const { HomeList } = useAppSelector((state) => state.articles);
  const { channel_id: activeId } = useAppSelector((state) => state.channel);
  const { pre_timestamp, results: list = [] } = HomeList[channel_id] || {};
  const dispatch = useDispatch();

  /** 异步函数 */
  async function mockRequest() {
    pre_timestamp
      ? await dispatch(
          SaveHomeListByIdAction(channel_id, Number(pre_timestamp))
        )
      : await dispatch(SaveHomeListByIdAction(channel_id));
  }

  /** 初始化请求 为了赋值pre_timestamp */
  useEffect(() => {
    if (Number(activeId) !== channel_id) return;
    if (list.length > 0) return;
    dispatch(SaveHomeListByIdAction(channel_id));
    // eslint-disable-next-line
  }, [channel_id, dispatch, activeId]);

  const handleRefresh = async () => {
    await dispatch(ClearListByIdAction(Number(channel_id)));
  };

  return (
    <PullToRefresh onRefresh={() => handleRefresh()}>
      <div style={{ padding: 10, paddingTop: 40 }} className="channel_list">
        {list?.map((item, index) => {
          return <ArticleItem ArticleData={item} key={index} />;
        })}
        <InfiniteScroll
          loadMore={mockRequest}
          /** 根据pre_timestamp值判断他是否有更多文章 */
          hasMore={!!pre_timestamp}
          style={{ marginBottom: 30 }}
        />
      </div>
    </PullToRefresh>
  );
}
